﻿using Handy_WPF.MVVM;
using HandyControl.Controls;
using HandyControl.Data;
using HandyControl.Tools.Extension;
using Kxx_API.DNS.ALI.Enum;
using Kxx_Common.Tools;
using Kxx_Domain.DNS;
using Kxx_Save.DNS;
using Kxx_Services.DNS;
using Kxx_Task.DNS;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace Handy_DNS.ViewModel
{
    internal class DomainRecordTaskViewModel : PageBaseViewModel<DomainRecordTaskExecModel>
    {
        DNSService dnsService;

        public DomainRecordTaskViewModel()
        {
            dnsService = new DNSService();

            recordTypeList = Enum.GetNames(typeof(RecordType));

            DataBind();
        }

        #region 属性
        private bool drawerOpen = false;
        /// <summary>
        /// 侧边栏打开状态
        /// </summary>
        public bool DrawerOpen
        {
            get
            {
                return drawerOpen;
            }
            set
            {
                drawerOpen = value;
                RaisePropertyChanged(nameof(DrawerOpen));
            }
        }

        private string drawerTitle = "Header";
        /// <summary>
        /// 侧边栏Title
        /// </summary>
        public string DrawerTitle
        {
            get { return drawerTitle; }
            set { drawerTitle = value; RaisePropertyChanged(nameof(DrawerTitle)); }
        }

        private string taskNumber;
        /// <summary>
        /// 操作任务编号
        /// </summary>
        public string TaskNumber
        {
            get { return taskNumber; }
            set { taskNumber = value; RaisePropertyChanged(nameof(TaskNumber)); }
        }

        private string recordId;
        /// <summary>
        /// 解析记录的ID
        /// </summary>
        public string RecordId
        {
            get { return recordId; }
            set { recordId = value; RaisePropertyChanged(nameof(RecordId)); }
        }

        private string rr;
        /// <summary>
        /// 主机记录
        /// </summary>
        public string RR
        {
            get { return rr; }
            set { rr = value; RaisePropertyChanged(nameof(RR)); }
        }

        private string type;
        /// <summary>
        /// 解析记录类型
        /// </summary>
        public string Type
        {
            get { return type; }
            set { type = value; RaisePropertyChanged(nameof(Type)); }
        }

        private int taskWaitTime = 300;
        /// <summary>
        /// 任务等待时间（s），默认5分钟
        /// </summary>
        public int TaskWaitTime
        {
            get { return taskWaitTime; }
            set { taskWaitTime = value; RaisePropertyChanged(nameof(TaskWaitTime)); }
        }

        private int notifyFrequency = 3;
        /// <summary>
        /// 状态通知频率（s），默认3秒钟
        /// </summary>
        public int NotifyFrequency
        {
            get { return notifyFrequency; }
            set { notifyFrequency = value; RaisePropertyChanged(nameof(NotifyFrequency)); }
        }

        private bool isRun = false;
        /// <summary>
        /// 任务状态控制
        /// </summary>
        public bool IsRun
        {
            get { return isRun; }
            set
            {
                isRun = value;

                RaisePropertyChanged(nameof(IsRun));
            }
        }

        public Array recordTypeList;
        /// <summary>
        /// 解析类型列表
        /// </summary>
        public Array RecordTypeList
        {
            get
            {
                return recordTypeList;
            }
        }
        #endregion

        #region 数据绑定
        /// <summary>
        /// 数据绑定
        /// </summary>
        private async void DataBind()
        {
            base.TotalCount = DNSLoad.RecordTaskList.Count;

            base.DataList = DNSLoad.RecordTaskList.Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList();
        }
        #endregion

        #region 命令
        private BaseCommand pageUpdatedCommand;
        /// <summary>
        /// 页码改变命令
        /// </summary>
        public BaseCommand PageUpdatedCommand
        {
            get
            {
                if (pageUpdatedCommand == null)
                {
                    pageUpdatedCommand = new BaseCommand(new Action<object>(o =>
                    {
                        int index = ((FunctionEventArgs<int>)o).Info;
                        base.PageIndex = index;
                        DataList = DNSLoad.RecordTaskList.Skip((index - 1) * PageSize).Take(PageSize).ToList();
                    }));
                }
                return pageUpdatedCommand;
            }
        }

        private BaseCommand addCommand;
        /// <summary>
        /// 添加命令
        /// </summary>
        public BaseCommand AddCommand
        {
            get
            {
                if (addCommand == null)
                {
                    addCommand = new BaseCommand(new Action<object>(o =>
                    {
                        DrawerOpen = true;
                        DrawerTitle = "添加";
                        TaskNumber = Guid.NewGuid().ToString();
                        RecordId = "";
                        RR = "";
                        Type = "";
                    }));
                }
                return addCommand;
            }
        }

        private BaseCommand editCommand;
        /// <summary>
        /// 编辑命令
        /// </summary>
        public BaseCommand EditCommand
        {
            get
            {
                if (editCommand == null)
                {
                    editCommand = new BaseCommand(new Action<object>(o =>
                    {
                        DrawerOpen = true;
                        DrawerTitle = "编辑";

                        DomainRecordTaskExecModel model = (DomainRecordTaskExecModel)o;
                        TaskNumber = model.TaskNumber;
                        RecordId = model.RecordId;
                        RR = model.RR;
                        Type = model.Type;
                        TaskWaitTime = model.TaskWaitTime;
                        NotifyFrequency = model.NotifyFrequency;
                        IsRun = model.IsRun;
                    }));
                }
                return editCommand;
            }
        }

        private BaseCommand delCommand;
        /// <summary>
        /// 删除命令
        /// </summary>
        public BaseCommand DelCommand
        {
            get
            {
                if (delCommand == null)
                {
                    delCommand = new BaseCommand(new Action<object>(o =>
                    {
                        DomainRecordTaskExecModel model = (DomainRecordTaskExecModel)o;

                        if (model != null)
                        {
                            model.Dispose();
                            DNSLoad.RecordTaskList.Remove(model);
                            Growl.Success($"任务【{model.TaskNumber}】删除成功");

                            DataBind();
                        }
                        else
                        {
                            Growl.Error($"任务【{model.TaskNumber}】删除失败，尝试删除空!");
                        }


                        SaveRecordTask();
                    }));
                }
                return delCommand;
            }
        }

        private BaseCommand saveCommand;
        /// <summary>
        /// 保存命令
        /// </summary>
        public BaseCommand SaveCommand
        {
            get
            {
                if (saveCommand == null)
                {
                    saveCommand = new BaseCommand(new Action<object>(o =>
                    {
                        #region 验证
                        if (TaskNumber.IsEmpty())
                        { 
                            Growl.Warning("任务编号为空!");
                            return;
                        }

                        if (RecordId.IsEmpty())
                        {
                            Growl.Warning("解析记录ID为空!");
                            return;
                        }
                        else if(!dnsService.GetRecordIsExists(RecordId))
                        {
                            Growl.Warning("解析记录ID不存在!");
                            return;
                        }

                        if (RR.IsEmpty())
                        {
                            Growl.Warning("主机记录为空!");
                            return;
                        }

                        if (Type.IsEmpty())
                        {
                            Growl.Warning("解析记录类型为空!");
                            return;
                        }
                        if (Array.IndexOf(Enum.GetNames(typeof(RecordType)), Type) == -1)
                        {
                            Growl.Warning("解析记录类型选择错误!");
                            return;
                        }

                        if (TaskWaitTime.ToInt() <= 0)
                        {
                            Growl.Warning("任务等待时间应大于0!");
                            return;
                        }

                        if (NotifyFrequency.ToInt() <= 0)
                        {
                            Growl.Warning("任务状态通知时间应大于0!");
                            return;
                        }
                        #endregion

                        DomainRecordTaskExecModel model = DNSLoad.RecordTaskList.Where(m => m.TaskNumber == this.TaskNumber).FirstOrDefault();

                        #region 新增
                        if (model == null)
                        {
                            model = new DomainRecordTaskExecModel(false) { 
                                TaskNumber = this.TaskNumber,
                                RecordId = this.RecordId,
                                RR = this.RR,
                                Type = this.Type,
                                TaskWaitTime = this.TaskWaitTime,
                                NotifyFrequency = this.NotifyFrequency,
                                IsRun = this.IsRun
                            };

                            DNSLoad.RecordTaskList.Add(model);

                            Growl.Success("新增成功");
                        }
                        #endregion
                        #region 编辑
                        else
                        {
                            model.TaskNumber = this.TaskNumber;
                            model.RecordId = this.RecordId;
                            model.RR = this.RR;
                            model.Type = this.Type;
                            model.TaskWaitTime = this.TaskWaitTime;
                            model.NotifyFrequency = this.NotifyFrequency;
                            model.IsRun = this.IsRun;

                            Growl.Success("编辑成功");
                        }
                        #endregion

                        SaveRecordTask();

                        DataBind();
                    }));
                }
                return saveCommand;
            }
        }
        #endregion

        #region 其他
        /// <summary>
        /// 保存解析任务
        /// </summary>
        private void SaveRecordTask()
        {
            List<DomainRecordTaskModel> list = new List<DomainRecordTaskModel>();

            foreach (var item in DNSLoad.RecordTaskList)
            {
                DomainRecordTaskModel model = new DomainRecordTaskModel();

                CopyHelper.CopyPropertiesTo(item, model);

                list.Add(model);
            }

            BascConfig.DomainRecordTask = list;
        }
        #endregion
    }
}
